using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using xVal.ServerSide;

namespace FwkLight.Web.Validation
{
  public static class DataAnnotationsValidationRunner
  {
    public static IEnumerable<ErrorInfo> GetErrors ( object instance )
    {
      IList<ErrorInfo> errorInfos = new List<ErrorInfo>();

      IEnumerable<PropertyDescriptor> descriptors = from prop in TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>() select prop;

      foreach (PropertyDescriptor prop in descriptors)
      {
        foreach (ValidationAttribute attribute in prop.Attributes.OfType<ValidationAttribute>())
        {
          if (!attribute.IsValid(prop.GetValue(instance)) && !prop.Name.EndsWith(".Id") && !prop.Name.Equals("Id"))
          {
            errorInfos.Add(new ErrorInfo(prop.Name, attribute.FormatErrorMessage(string.Empty), instance));
          }
        }
      }

      return errorInfos;
    }
  }
}